package com.dataStructure.线性表.链表;

import com.dataStructure.线性表.list_父类.AbstractList;

public class LinkedList_带虚拟头结点<E> extends AbstractList<E> {

    public LinkedList_带虚拟头结点(){
        first = new Node<>(null,null);
    }

    private Node<E> first;

    private static class Node<E> {
        E element;
        Node<E> next;

        public Node(E element, Node<E> next) {
            this.element = element;
            this.next = next;
        }
    }

    @Override
    public void clear() {
        size = 0;
        first = null;
    }

    @Override
    public boolean contains(E element) {
        return false;
    }

    @Override
    public E get(int index) {
        return node(index).element;
    }

    @Override
    public E set(int index, E element) {
        Node<E> node = node(index);
        E old = node.element;
        node.element = element;
        return old;
    }

    @Override
    public void add(int index, E element) {
            Node<E> prev =index==0?first:node(index - 1);
            prev.next = new Node<E>(element, prev.next);
        size++;
    }


    @Override
    public E remove(int index) {
        rangeCheck(index);
            Node<E> prev =index==0?first: node(index - 1);
           Node<E> node = prev.next;
            prev.next = node.next;
        size --;
        return node.element;
    }

    @Override
    public int indexOf(E element) {
        if (element == null){
            Node<E> node = this.first;
            for (int i = 0; i < size; i++) {
                if (node.element == null) return i;
               node = node.next;
            }
        }
        Node<E> node = this.first;
        for (int i = 0; i < size; i++) {
            if (element.equals(node.element)) return i;
        }
        return ELEMENT_NOT_FOUND;
    }

    //获取索引处的节点
    private Node<E> node(int index) {
        rangeCheck(index);
        Node<E> node = first.next;
        for (int i = 0; i < index; i++) {
            node = node.next;
        }
        return node;
    }

    @Override
    public String toString() {
        StringBuilder string = new StringBuilder();
        Node<E> node = first.next;
        string.append("size=").append(size).append(",[");
        for (int i = 0; i < size; i++) {
            if (i != 0) {
                string.append(", ");
            }
            string.append(node.element);
          /*  if (i != size -1){
                string.append(",");
            }*/
          node = node.next;
        }
        string.append("]");

        return string.toString();
    }
}
